<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="25%"
    :before-close="handleClose"
  >
    <el-form :model="form" ref="formRef" :rules="rules" label-width="80px">
      <el-form-item label="文字信息" prop="codeTitle">
        <el-input v-model="form.codeTitle" placeholder="请输入文字信息" />
      </el-form-item>

      <el-form-item label="图片" prop="url">
        <el-upload
          class="qrcode-upload"
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleQrcodeChange"
          accept="image/jpeg,image/png,image/gif,image/jpg"
        >
          <div class="upload-content">
            <template v-if="form.url">
              <el-image :src="form.url" fit="cover" class="preview-image" />
              <div class="delete-icon" @click.stop="handleImageRemove">
                <el-icon><Delete /></el-icon>
              </div>
            </template>
            <div v-else class="upload-placeholder">
              <el-icon class="upload-icon"><Upload /></el-icon>
              <div class="upload-text">上传图片</div>
              <div class="upload-tip">点击上传</div>
            </div>
          </div>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, computed } from 'vue';
import { Upload, Delete } from '@element-plus/icons-vue';
import { uploadPic } from '@/api/Upload/upload';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  editData: {
    type: Object,
    default: null,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(['update:visible', 'confirm', 'cancel']);

const dialogVisible = ref(props.visible);
const formRef = ref(null);

// 表单验证规则
const rules = {
  codeTitle: [{ required: true, message: '请输入文字信息', trigger: 'blur' }],
  url: [{ required: true, message: '请上传二维码图片', trigger: 'change' }],
};

const form = ref({
  codeTitle: '',
  url: '',
});

// 监听visible变化
watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal;
  }
);

// 监听dialog自身值变化
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal);
});

// 监听编辑数据变化
watch(
  () => props.editData,
  (newVal) => {
    if (newVal) {
      form.value = { ...newVal };
    }
  }
);

// 修改对话框标题
const dialogTitle = computed(() =>
  props.isEdit ? '编辑二维码信息' : '添加二维码信息'
);

// 添加图片格式校验函数
const validateImageType = (file) => {
  const acceptedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];
  if (!acceptedTypes.includes(file.type)) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片！');
    return false;
  }
  return true;
};

// 修改二维码图片上传处理
const handleQrcodeChange = async (file) => {
  if (!validateImageType(file.raw)) {
    return;
  }

  const formData = new FormData();
  formData.append('picture', file.raw);

  try {
    const response = await uploadPic(formData);
    if (response.data.code === 200) {
      if (typeof response.data.data === 'object') {
        form.value.url = response.data.data.url;
      } else {
        form.value.url = response.data.data;
      }

      ElMessage({
        message: '上传成功',
        type: 'success',
      });
    } else {
      ElMessage({
        message: response.data.msg || '上传失败',
        type: 'error',
      });
    }
  } catch (error) {
    console.error('上传失败:', error);
    ElMessage({
      message: '上传失败',
      type: 'error',
    });
  }
};

const handleConfirm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      emit('confirm', form.value);
      handleClose();
    } else {
      ElMessage({
        message: '请填写完整所有必填项',
        type: 'warning',
      });
      return false;
    }
  });
};

const handleCancel = () => {
  formRef.value?.resetFields();
  handleClose();
};

const handleClose = () => {
  formRef.value?.resetFields();
  form.value = {
    codeTitle: '',
    url: '',
  };
  emit('update:visible', false);
};

const handleImageRemove = () => {
  form.value.url = '';
};
</script>

<style lang="scss" scoped>
.qrcode-upload {
  display: block;
  width: 150px;
  height: 150px;

  :deep(.el-upload) {
    width: 100%;
    height: 100%;
  }

  .upload-content {
    width: 100%;
    height: 100%;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;

    &:hover {
      border-color: #409eff;

      .delete-icon {
        opacity: 1;
      }
    }

    .preview-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
      display: block;
      position: absolute;
      top: 0;
      left: 0;
    }

    .delete-icon {
      position: absolute;
      top: 0;
      right: 0;
      width: 24px;
      height: 24px;
      background-color: rgba(0, 0, 0, 0.5);
      color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      opacity: 0;
      transition: opacity 0.3s;
      border-bottom-left-radius: 4px;
      z-index: 1;

      &:hover {
        background-color: rgba(0, 0, 0, 0.7);
      }
    }

    .upload-placeholder {
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #8c8c8c;
      background-color: #fff;

      .upload-icon {
        font-size: 28px;
        margin-bottom: 8px;
      }

      .upload-text {
        font-size: 14px;
        margin-bottom: 4px;
      }

      .upload-tip {
        font-size: 12px;
        color: #909399;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
